/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yuanxin.chooseimage.zxing;

import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;

import com.google.zxing.ResultPoint;
import com.yuanxin.chooseimage.R;
import com.yuanxin.chooseimage.zxing.camera.CameraManager;

import java.util.ArrayList;
import java.util.List;

/**
 * This view is overlaid on top of the camera preview. It adds the viewfinder rectangle and partial
 * transparency outside it, as well as the laser scanner animation and result points.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class ViewfinderView extends View {

    private static final String TAG = ViewfinderView.class.getName();

    //    private static final int[] SCANNER_ALPHA = {0, 64, 128, 192, 255, 192, 128, 64};
    private static final long ANIMATION_DELAY = 100L;
    //    private static final int CURRENT_POINT_OPACITY = 0xA0;
//    private static final int MAX_RESULT_POINTS = 20;
    private static final int POINT_SIZE = 6;

    //    private CameraManager cameraManager;
    private final Paint paint;
    private final Paint paintDefault;
    private final int maskColor;
    //    private final int resultPointColor;
//    private int scannerAlpha;
//    private List<ResultPoint> possibleResultPoints;
    private int scanWidth = 600;
    private int scanHeight = 600;

    /**
     * 滚动线条位置属性
     */
    private int slideTop = 0;

    /**
     * 是否初始化
     */
    private boolean isInit = false;

    /**
     *
     */
    private int ScreenRate;

    /**
     *
     */
    private final int CORNER_WIDTH = 10;

    /**
     *
     */
    private float density;

    /**
     *
     */
    private Bitmap scanLine;
    /**
     *
     */
    private Bitmap scanFrame;


    public void setScanHeight(int scanHeight) {
        this.scanHeight = scanHeight;
    }

    public void setScanWidth(int scanWidth) {
        this.scanWidth = scanWidth;
    }

    // This constructor is used when the class is built from an XML resource.
    public ViewfinderView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Initialize these once for performance rather than calling them every time in onDraw().
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintDefault = new Paint(Paint.ANTI_ALIAS_FLAG);
        Resources resources = getResources();
        maskColor = resources.getColor(R.color.viewfinder_mask);
//        resultPointColor = resources.getColor(R.color.possible_result_points);
//        scannerAlpha = 0;
//        possibleResultPoints = new ArrayList<>(5);


        density = context.getResources().getDisplayMetrics().density;
        ScreenRate = (int) (20 * density);

    }


    private Bitmap changeBitmapSize(int resId, int newWidth, int newHeight) {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Log.i("width", "width:" + width);
        Log.i("height", "height:" + height);

        //计算压缩的比率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        if (newWidth == -1) {
            scaleWidth = scaleHeight;
        }
        if (newHeight == -1) {
            scaleHeight = scaleWidth;
        }
        //获取想要缩放的matrix
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        //获取新的bitmap
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.getWidth();
        bitmap.getHeight();
        Log.e("newWidth", "newWidth" + bitmap.getWidth());
        Log.e("newHeight", "newHeight" + bitmap.getHeight());
        return bitmap;
    }


//    public void setCameraManager(CameraManager cameraManager) {
//        this.cameraManager = cameraManager;
//    }

    int width;
    int height;


    int myT;
    int myB;

    int myL;
    int myR;


    @SuppressLint("DrawAllocation")
    @Override
    public void onDraw(Canvas canvas) {
        if (!isInit) {
            isInit = true;
            width = canvas.getWidth();
            height = canvas.getHeight();

            myT = (height - scanHeight) / 2;

            myB = myT + scanHeight;

            myL = (width - scanWidth) / 2;
            myR = myL + scanWidth;

            slideTop = myT + CORNER_WIDTH;

            scanFrame = changeBitmapSize(R.drawable.scan_frame, scanWidth, scanHeight);
            scanLine = changeBitmapSize(R.drawable.scan_line, width, -1);
        }

        // Draw the exterior (i.e. outside the framing rect) darkened
        paint.setColor(maskColor);
        //上下左右阴影遮罩区域
        canvas.drawRect(0, 0, width, myT, paint);//上
        canvas.drawRect(0, myT, myL, myB, paint);//左
        canvas.drawRect(myR, myT, width, myB, paint);//右
        canvas.drawRect(0, myB, width, height, paint);//下

        Rect frameSrc = new Rect(0, 0, scanWidth, scanWidth);
        Rect frameDsc = new Rect(myL, myT, myR, myB);

        canvas.drawBitmap(scanFrame, frameSrc, frameDsc, paintDefault);

        Rect lineSrc = new Rect(0, 0, width, 8);
        Rect lineDsc = new Rect(myL, slideTop - 4, myR, slideTop + 4);

        canvas.drawBitmap(scanLine, lineSrc, lineDsc, paintDefault);
        if (!isStart) {
            isStart = true;
            start();
        }
    }

    public void drawViewfinder() {
        invalidate();
    }

    private boolean isStart = false;

    public void start() {
        final ValueAnimator animator = ValueAnimator.ofInt(myT, myB);
        animator.setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setRepeatMode(ValueAnimator.RESTART);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if (slideTop != (int) animation.getAnimatedValue()) {
                    slideTop = (int) animation.getAnimatedValue();
                    invalidate();
                }
            }
        });
        animator.start();
    }


    public void addPossibleResultPoint(ResultPoint point) {
//        List<ResultPoint> points = possibleResultPoints;
//        synchronized (points) {
//            points.add(point);
//            int size = points.size();
//            if (size > MAX_RESULT_POINTS) {
//                // trim it
//                points.subList(0, size - MAX_RESULT_POINTS / 2).clear();
//            }
//        }
    }

}